<template>
  <div id="index" ref="appRef" @dblclick="screen">
    <div class="bg">
      <dv-loading v-if="loading">Loading...</dv-loading>
      <div v-else class="host-body">
        <!-- 头部 -->
        <pheader @changeCom="showComModal = true"></pheader>
        <div v-if="showComModal" class="all-model">
          <div class="model-view-box">
            <dv-border-box-11 title="选择系统" style="width: 800px;">
              <div class="c-box">
                <div v-for="item in poromissList" :key="item.id" class="item"
                  :class="item.id === companyLabFlag ? 'active' : ''" @click="checkCompnay(item.id)">
                  {{ item.name }}
                </div>
              </div>
            </dv-border-box-11>
          </div>
        </div>
        <div v-else class="body-box">
          <div class="body-first">
            <div class="body-left">
              <div class="view-box b" :class="modelName === 'one' ? 'z100' : ''">
                <div class="box-title">
                  <div class="text flex">选择数据范围
                    <Select :options="YeardataList" v-model="oneData" @change="timeChecked(false)" />
                    <div class="detail-b">
                      <div class="detail" @click="timeChecked(true)">详情表格</div>
                    </div>
                  </div>
                  <div class="line"></div>
                </div>
                <div class="data-box">
                  <scope :TestMainId="oneData" :LabFlag="companyLabFlag" :LabName="LabName" :LabId="LabId"
                    :LabType="LabType"></scope>
                </div>
              </div>
              <div class="view-box b" :class="modelName === 'there' ? 'z100' : ''">
                <div class="box-title">
                  <div class="text flex">可疑数据
                    <div class="detail-b">
                      <div class="detail" @click="timeCheckedThere(null)">详情表格</div>
                    </div>
                  </div>
                  <div class="line"></div>
                </div>
                <div class="data-box">
                  <suspicious v-if="SuspiciousData" :SuspiciousData="SuspiciousData"></suspicious>
                </div>
              </div>
            </div>
            <div class="body-center">
              <div class="box-title">
                <div class="text">实验室地区位置分布图</div>
                <div class="line"></div>
              </div>
              <div class="data-box">
                <MapData :companyLabFlag="companyLabFlag"></MapData>
              </div>
            </div>
            <div class="body-right">
              <div class="view-box b">
                <div class="box-title">
                  <div class="text flex">所选实验室数据分析
                    <Select :disabled="disabled" :options="compnayList" v-model="moreParams.LabId" @change="timeFun" />
                    <vxe-select v-model="timeList" placeholder="多选" clearable multiple @change="timeFun"
                      style="width:120px">
                      <vxe-option v-for="time in YeardataList" :key="time.value" :value="time.value"
                        :label="time.label"></vxe-option>
                    </vxe-select>
                  </div>
                  <div class="line"></div>
                </div>
                <div class="data-box">
                  <analyse v-if="SuspiciousAndOutlierData" :SuspiciousAndOutlierData="SuspiciousAndOutlierData">
                  </analyse>
                </div>
              </div>
              <div class="view-box b">
                <div class="box-title">
                  <div class="text">问题数据占比</div>
                  <div class="line"></div>
                </div>
                <div class="data-box">
                  <problem v-if="ProblemData" :ProblemData="ProblemData"></problem>
                </div>
              </div>
            </div>
          </div>
          <div class="body-last">
            <div class="view-box">
              <div class="box-title">
                <div class="text">离群数据</div>
                <div class="line"></div>
              </div>
              <div class="data-box">
                <withdrawn v-if="OutlierData" :OutlierData="OutlierData"></withdrawn>
              </div>
            </div>
            <div class="view-box" :class="modelName === 'two' ? 'z100' : ''">
              <div class="box-title">
                <div class="text flex">可疑数据/离群数据（占比）
                  <div class="detail-b">
                    <div class="detail" @click="timeCheckedTwo(null)">详情表格</div>
                  </div>
                </div>
                <div class="line"></div>
              </div>
              <div class="data-box">
                <withorsus v-if="SuspiciousOutlierData" :SuspiciousOutlierData="SuspiciousOutlierData"></withorsus>
              </div>
            </div>
            <div class="view-box">
              <div class="box-title">
                <div class="text flex">结果优秀占比
                  <Select :options="YeardataList" v-model="resultData" @change="timeChecked(false)" />
                </div>
                <div class="line"></div>
              </div>
              <div class="data-box">
                <result :TestMainId="resultData" :companyLabFlag="companyLabFlag"></result>
              </div>
            </div>
            <div class="view-box">
              <div class="box-title">
                <div class="text">实验室历年数据变化趋势</div>
                <div class="line"></div>
              </div>
              <div class="data-box">
                <trend v-if="ItemDataResult" :ItemDataResult="ItemDataResult"></trend>
              </div>
            </div>
          </div>
        </div>
        <div v-if="shoModel" class="model-view">
          <div v-if="modelName === 'one'" class="model one">
            <div class="close" @click="closeModel">返回</div>
            <Jointable :datas="ReproducibilityData"></Jointable>
          </div>
          <div v-else-if="modelName === 'two'" class="model">
            <div class="close" @click="closeModel">返回</div>
            <TwoTable :datas="ReproducibilityData" :dataList="YeardataList" @timeCheckedTwo="timeCheckedTwo"
              :time="twoData"></TwoTable>
          </div>
          <div v-else-if="modelName === 'there'" class="model there">
            <div class="close" @click="closeModel">返回</div>
            <ThereTable :datas="ReproducibilityData" :dataList="YeardataList" @timeCheckedTwo="timeCheckedThere"
              :time="thereData"></ThereTable>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script lang="ts">
import { defineComponent, ref, reactive, onMounted, onUnmounted, toRefs, computed } from "vue"
import { formatTime } from "@/utils/index"
import { WEEK } from "@/constant/index"
import useDraw from "@/utils/useDraw"
import { title, subtitle, moduleInfo } from "@/constant/index"
import pheader from "@/components/pheader/pheader.vue"
import MapData from "../map/MapData.vue"
import suspicious from '../suspicious/suspicious.vue'
import withdrawn from '../withdrawn/withdrawn.vue'
import withorsus from '../withorsus/withorsus.vue'
import analyse from '../analyse/analyse.vue'
import problem from '../problem/problem.vue'
import trend from '../trend/trend.vue'
import result from '../result/result.vue'
import scope from '../scope/scope.vue'
import API from '@/common/api'
import Jointable from '@/components/table/Jointable.vue'
import TwoTable from '@/components/table/TwoTable.vue'
import ThereTable from '@/components/table/ThereTable.vue'
import Select from '@/components/Select.vue'
import screenfull from 'screenfull'

export default defineComponent({
  components: {
    pheader,
    MapData,
    suspicious,
    withdrawn,
    withorsus,
    analyse,
    problem,
    trend,
    result,
    scope,
    Jointable,
    TwoTable,
    Select,
    ThereTable
  },
  setup() {

    const fullScreen = ref(false)
    const allData = reactive({
      SuspiciousData: null,//可疑数据
      OutlierData: null,//离群数据
      SuspiciousOutlierData: null,//离群数据/可疑数据占比
      ItemDataResult: null,
      ProblemDataTotalCount: 0,
      SuspiciousAndOutlierData: null,
      ProblemData: null,
      ReproducibilityData: []
    })
    const LabName = ref('')
    const LabId = ref('')
    const selectOption = ref('')
    const oneData = ref('')
    const twoData = ref('')
    const thereData = ref('')
    const resultData = ref('')
    const timeList = ref([])
    const YeardataList = ref([])
    const compnayList = ref([])
    const companyLabFlag = ref(-1)
    const poromissList = ref([])
    const showComModal = ref(false)
    const LabType = ref('')
    const moreParams = ref(
      {
        "TestMainIdList": [
          {
            "TestMainId": "",//年份对应的ID
            "TestYear": '' //年份
          }
        ],
        //登录返回的LabInfo 数据，页面是可以选择哪个化验室的
        "LCode": "", //实验室代码
        "LabId": "" //实验室ID 
      }
    )

    const screen = () => {
      screenfull.toggle()
      // ElMessage('全屏啦')
    }
    // * 加载标识
    const loading = ref<boolean>(true)
    // * 时间内容
    const timeInfo = reactive({
      setInterval: 0,
      dateDay: "",
      dateYear: "",
      dateWeek: "",
    })
    const shoModel = ref(false)
    const modelName = ref('')
    // * 适配处理
    const { appRef, calcRate, windowDraw, unWindowDraw } = useDraw()
    const disabled = computed(() => {
      const iindex = compnayList.value.findIndex(e => e.value === LabId.value)
      return companyLabFlag.value === 0 || iindex < 0
    })
    // 生命周期
    onMounted(() => {
      const data = localStorage.getItem('info')
      if (data) {
        const datatem = JSON.parse(data)
        YeardataList.value = datatem.Yeardata.map((e) => {
          const item = {
            label: e.TestYear,
            value: e.TestMainId
          }
          return item
        })

        compnayList.value = datatem.LabInfo.map((e) => {
          const item = {
            label: e.ShortName,
            value: e.Id,
            code: e.LCode
          }
          return item
        })
        timeList.value = YeardataList.value.map((e) => e.value)
        oneData.value = YeardataList.value[0].value
        twoData.value = YeardataList.value[0].value
        resultData.value = YeardataList.value[0].value
        thereData.value = YeardataList.value[0].value
        LabType.value = datatem.LabType
        LabName.value = datatem.ShortName
        LabId.value = datatem.Id
        if (datatem.LabFlag === 0) {
          poromissList.value = [{ id: 0, name: '本公司' }]
        } else if (datatem.LabFlag === 1) {
          poromissList.value = [{ id: 0, name: '本公司' }, { id: 1, name: '总公司' }]
        } else if (datatem.LabFlag === 2) {
          poromissList.value = [{ id: 0, name: '本公司' }, { id: 2, name: '地区公司' }]
        } else {
          poromissList.value = [{ id: 0, name: '本公司' }, { id: 1, name: '总公司' }, { id: 2, name: '地区公司' }]
        }
        moreParams.value = {
          "TestMainIdList": [
            {
              "TestMainId": YeardataList.value[0].value,//年份对应的ID
              "TestYear": YeardataList.value[0].label //年份
            }
          ],
          //登录返回的LabInfo 数据，页面是可以选择哪个化验室的
          "LCode": datatem.LCode, //实验室代码
          "LabId": datatem.Id //实验室ID 
        }
        const flag = sessionStorage.getItem('companyLabFlag')
        if (datatem.LabFlag !== 0 && flag === null) {
          showComModal.value = true
        } else {
          companyLabFlag.value = Number(flag)
          GetSuspiciousDataChartFun()
          GetLabDataChart()
        }
      }
      cancelLoading()
      handleTime()
      // todo 屏幕适应
      windowDraw()
      calcRate()
    })

    onUnmounted(() => {
      unWindowDraw()
      clearInterval(timeInfo.setInterval)
    })

    // methods
    const GetSuspiciousDataChartFun = async () => {
      allData.SuspiciousOutlierData = null
      allData.OutlierData = null
      allData.SuspiciousData = null
      const data = localStorage.getItem('info')
      if (data) {
        const loaclData = JSON.parse(data)
        let Yeardata = loaclData.Yeardata
        let LocalYeardata = loaclData.LocalYeardata
        let res: any = null

        if (companyLabFlag.value === 1) {
          res = await API.GetSuspiciousDataChart({ Yeardata })
        } else {
          const params = {
            "Yeardata": companyLabFlag.value === 0 ? LocalYeardata : Yeardata,
            "LabFlag": companyLabFlag.value,  //传0 表示本化验室  2 表示地区公司    
            "LabType": loaclData.LabType,//登录返回的化验类型
            "LabId": loaclData.Id,//登录返回的化验室的ID
            "LabName": loaclData.ShortName// 登录返回的化验室的名称
          }
          res = await API.GetLocalSuspiciousDataChart(params)
        }

        if (res.Tag) {
          allData.SuspiciousOutlierData = res.Data.SuspiciousOutlierData
          allData.OutlierData = res.Data.OutlierData
          allData.SuspiciousData = res.Data.SuspiciousData
        }
      }
    }
    const checkCompnay = (id) => {
      showComModal.value = false
      companyLabFlag.value = id
      sessionStorage.setItem('companyLabFlag', id)
      GetSuspiciousDataChartFun()
      GetLabDataChart()
    }

    // 根据实验室和年份筛选数据
    const GetLabDataChart = async () => {
      allData.ProblemData = null //问题占比数据
      allData.SuspiciousAndOutlierData = null  // 可疑和离群数据次数
      allData.ItemDataResult = null  // 可年底数据变化趋势 数据
      moreParams.value.TestMainIdList = timeList.value.map((e) => {
        const data = YeardataList.value.find((f) => f.value === e)
        if (data) {
          return {
            "TestMainId": data.value,//年份对应的ID
            "TestYear": data.label //年份
          }
        }
      })

      const res: any = await API.GetLabDataChart(moreParams.value)
      if (res.Tag) {
        allData.ProblemDataTotalCount = res.Data.ProblemDataTotalCount //问题占比总数
        allData.ProblemData = res.Data.ProblemData //问题占比数据
        allData.SuspiciousAndOutlierData = res.Data.SuspiciousAndOutlierData // 可疑和离群数据次数
        allData.ItemDataResult = res.Data.ItemDataResult // 可年底数据变化趋势 数据
      }
    }

    // todo 处理 loading 展示
    const cancelLoading = () => {
      setTimeout(() => {
        loading.value = false
      }, 500)
    }

    // todo 处理时间监听
    const handleTime = () => {
      timeInfo.setInterval = setInterval(() => {
        const date = new Date()
        timeInfo.dateDay = formatTime(date, "HH: mm: ss")
        timeInfo.dateYear = formatTime(date, "yyyy-MM-dd")
        timeInfo.dateWeek = WEEK[date.getDay()]
      }, 1000)
    }

    const timeChecked = (type) => {
      modelName.value = 'one'
      if (shoModel.value || type) {
        GetReproducibilityDataFun()
      }
    }

    const closeModel = () => {
      shoModel.value = false
      modelName.value = ''
    }

    const timeCheckedThere = (value) => {
      modelName.value = 'there'
      if (value) {
        thereData.value = value
      }
      GetReproducibilityDataFun()
    }

    const timeFun = () => {
      const LCode = compnayList.value.find(e => e.value === moreParams.value.LabId)
      moreParams.value.LCode = LCode.code
      GetLabDataChart()
    }

    const timeCheckedTwo = (value) => {
      modelName.value = 'two'
      if (value) {
        twoData.value = value
      }
      GetReproducibilityDataFun()

    }
    const GetReproducibilityDataFun = async () => {
      if (modelName.value === 'one') {
        const res: any = await API.GetReproducibilityData({ "TestMainId": oneData.value })
        if (res.Tag) {
          shoModel.value = true
          allData.ReproducibilityData = res.Data.ReproducibilityData
        }
      } else if (modelName.value === 'two') {
        const res: any = await API.GetOverallData({ "TestMainId": twoData.value })
        if (res.Tag) {
          shoModel.value = true
          allData.ReproducibilityData = res.Data
        }
      } else if (modelName.value === 'there') {
        const res: any = await API.GetSuspiciousData({ "TestMainId": thereData.value })
        if (res.Tag) {
          shoModel.value = true
          allData.ReproducibilityData = res.Data
        }
      }
    }

    // return
    return {
      loading,
      timeInfo,
      appRef,
      title,
      subtitle,
      moduleInfo,
      ...toRefs(allData),
      GetReproducibilityDataFun,
      shoModel,
      YeardataList,
      oneData,
      timeChecked,
      selectOption,
      closeModel,
      modelName,
      LabId,
      LabName,
      moreParams,
      timeCheckedTwo,
      twoData,
      thereData,
      timeCheckedThere,
      timeList,
      timeFun,
      resultData,
      compnayList,
      companyLabFlag,
      poromissList,
      checkCompnay,
      showComModal,
      LabType,
      disabled,
      screen
    }
  },
})
</script>

<style lang="scss" scoped>
@import "@/assets/scss/index.scss";

.flex {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.detail-b {
  position: relative;
  width: 100px;

  .detail {
    top: -18px;
    right: 0;
    position: absolute;
    cursor: pointer;
    border: 1px solid #ffffff92;
    background-color: #1C5BEC;
    font-size: 14px;
    height: 32px;
    display: flex;
    align-items: center;
    padding: 0px 6px;
  }
}

.dropdown:hover .dropdown-content {
  display: block;
}

.z100 {
  position: relative;
  z-index: 1001;
}

.model-view {
  position: fixed;
  left: 0;
  top: 0;
  right: 0;
  bottom: 0;
  z-index: 1000;
  display: flex;
  align-items: center;
  justify-content: center;
  background: rgba(0, 0, 0, 0.75);

  .model {
    &.one {
      margin-left: 100px;
      width: 1000px;
    }

    &.there {
      margin-left: 450px;
      width: 1400px;
    }

    margin-left: 900px;
    position: absolute;
    width: 900px;
    max-height: 90vh;
    min-height: 50vh;
    background: url('../../assets/images/model.png');
    background-size: 100% 100%;
    padding: 30px 30px 40px;

    .close {
      position: absolute;
      right: 30px;
      font-size: 24px;
      cursor: pointer;
    }
  }
}

::v-deep(.vxe-input--inner) {
  color: #ffffff;
  background-color: #0A4FE8;
}

::v-deep(.vxe-select--panel-wrapper) {
  background-color: #0A4FE8;
  color: #ffffff;
}

::v-deep(.vxe-select-option) {
  &.is--hover {
    background-color: #25435f;
    color: #ffffff;
  }

  &.is--selected {
    background-color: #5aa2e0;
    color: #ffffff;
  }
}

.all-model {
  position: fixed;
  left: 0;
  right: 0;
  bottom: 0;
  top: 0;
  z-index: 1000;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: rgba(0, 0, 0, 0.75);

  .model-view-box {
    width: 800px;
    height: 500px;
    display: flex;
    align-items: center;
    justify-content: center;

    .c-box {
      margin-top: 30px;
      width: 800px;
      height: 500px;
      display: flex;
      flex-direction: column;
      align-items: center;
      justify-content: center;

      .item {
        &:hover {
          font-size: 24px;
          color: #2a64f5;
        }

        &.active {
          background: #416fe3;
          font-size: 24px;
          color: #ffffff !important;
        }

        transition: all 0.3s;
        cursor: pointer;
        width: 700px;
        height: 100px;
        border: 1px solid rgb(138, 170, 251);
        margin-bottom: 20px;
        display: flex;
        align-items: center;
        justify-content: center;
        font-size: 18px;
        font-weight: bold;
      }
    }

  }

}
</style>
